﻿/*
 * 由SharpDevelop创建。
 * 用户： Administrator
 * 日期: 2024/6/21
 * 时间: 13:19
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using EpubSharp;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Text;

namespace woo
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		[DllImport("user32.dll")]
	    public static extern bool ReleaseCapture();
	    [DllImport("user32.dll")]
	    public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
	    [DllImport("user32", EntryPoint = "HideCaret")]
		private static extern bool HideCaret(IntPtr hWnd);
	  
	    int h=0;
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			richTextBox1.AllowDrop = true;
			richTextBox1.DragEnter += new DragEventHandler(richTextBox1_DragEnter);
            richTextBox1.DragDrop += new DragEventHandler(richTextBox1_DragDrop);
			richTextBox1.BackColor=Color.FromArgb(245,247,249);
			SetScrollBar(this.richTextBox1.Handle,3, 0); 
			HideCaret(richTextBox1.Handle);
			
			h=this.Height;
			
			LoadRememberedTxt();
			string file = BaseDirectory + "History.txt";
                if (File.Exists(file))
                {
                	string[] txt=File.ReadAllLines(file);
                	//MessageBox.Show(txt);
                	FindTags(txt[0]);
                }
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}
		void Panel1MouseDown(object sender, MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Left)
            { 
                //这里一定要判断鼠标左键按下状态，否则会出现一个很奇葩的BUG，不信邪可以试一下~~
                ReleaseCapture();
                SendMessage(Handle, 0x00A1, 2, 0);
              //   SendMessage(this.Handle, VM_NCLBUTTONDOWN_, HTCAPTION_, 0);
			}
		}
		
		//隐藏滑动条
		   [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int ShowScrollBar(IntPtr hWnd, int bar, int show);


        private class SubWindow : NativeWindow
        {
            private int m_Horz = 0;
            private int m_Show = 0;

            public SubWindow(int p_Horz, int p_Show)
            {
                m_Horz = p_Horz;
                m_Show = p_Show;
            }
            protected override void WndProc(ref Message m_Msg)
            {
                ShowScrollBar(m_Msg.HWnd, m_Horz, m_Show);
                base.WndProc(ref m_Msg);
            }
        }
		/// <summary>
        /// 设置滚动条是否显示  zgke@sina.com qq:116149
        /// </summary>
        /// <param name="p_ControlHandle">句柄</param>
        /// <param name="p_Horz">0横 1列 3全部</param>
        /// <param name="p_Show">0隐 1显</param>
        public static void SetScrollBar(IntPtr p_ControlHandle, int p_Horz, int p_Show)
        {
            SubWindow _SubWindow = new SubWindow(p_Horz, p_Show);
            _SubWindow.AssignHandle(p_ControlHandle);
        }
		
        private void richTextBox1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
 
        private void richTextBox1_DragDrop(object sender, DragEventArgs e)
        {
            string file = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();//获得路径
            if (File.Exists(file))
            {
                string Extension = System.IO.Path.GetExtension(file).ToLower();
                if (Extension == ".txt")
                {
                    notifyIcon1.Text= System.IO.Path.GetFileName(file);
                    this.richTextBox1.LoadFile(file, RichTextBoxStreamType.PlainText);//读取txt文件
                    RememberTxt(file);//记录txt文件的路径
                    LoadChapter(file);//读取章节
               //     DeleteBookmark();//删除书签(防止打开B小说，却加载了A小说书签的bug)
                }else if (Extension == ".epub") {
                	EpubBook book = EpubReader.Read(file);
			
					// Read metadata
					string title = book.Title;
					notifyIcon1.Text= title ;
					 
					 string text = book.ToPlainText();
					 richTextBox1.Text=text;
                    
                    RememberTxt(file);//记录txt文件的路径
                    LoadChapter2(text);//读取章节
                 //  DeleteBookmark();//删除书签(防止打开B小说，却加载了A小说书签的bug)
                }
            }
        }
         //读取章节
        public void LoadChapter(string file)
        {
        	//contentsToolStripMenuItem.DropDownItems.Clear();
            try
            {
              //  this.listBox1.Items.Clear();
                if (File.Exists(file))
                {
                    FileStream fs = new FileStream(file, FileMode.Open);
                    using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default))
                    {
                        string strLine = sr.ReadLine(); //读取文件中的一行
                        string t="";
                        while (strLine != null)
                        {
                        	
                            string[] patArr = { "第(.*?)章", "第(.*?)回", "第(.*?)集", "第(.*?)卷", "第(.*?)部", "第(.*?)篇", "第(.*?)节", "第(.*?)季" };
                            foreach (var pattern in patArr)
                            {
                                Regex reg = new Regex(pattern);
                                if (reg.IsMatch(strLine))
                                {
                                    if (strLine.Length < 20)//超过20个字的标题，可能是小说里面出现的“书中书、文中文”...
                                    {
                                    	t=strLine.Trim().Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
                                    	 
						                ToolStripItem fd = contentsToolStripMenuItem.DropDownItems.Add(t);
						
						                fd.Click += new System.EventHandler(ContentsToolStripMenuItemClick);
                                       // this.listBox1.Items.Add(strLine.Trim().Replace("\r\n", "").Replace("\r", "").Replace("\n", ""));//添加标题行
                                    }
                                    continue;
                                }                             
                            }
                            strLine = sr.ReadLine();
                            //Thread.Sleep(1);
                        }
                       // MessageBox.Show(t);
                    }
                }
            }
            catch { }
        }
        //读取章节
        public void LoadChapter2(string txt)
        {
        	//contentsToolStripMenuItem.DropDownItems.Clear();
            try
            {
              MemoryStream stream = new MemoryStream();
              StreamWriter writer = new StreamWriter( stream );
				writer.Write( txt );
				writer.Flush();
              stream.Position = 0;
				StreamReader sr = new StreamReader( stream );
                     
                        string strLine = sr.ReadLine(); //读取文件中的一行
                        string t="";
                        while (strLine != null)
                        {
                        	
                            string[] patArr = { "第(.*?)章", "第(.*?)回", "第(.*?)集", "第(.*?)卷", "第(.*?)部", "第(.*?)篇", "第(.*?)节", "第(.*?)季" };
                            foreach (var pattern in patArr)
                            {
                                Regex reg = new Regex(pattern);
                                if (reg.IsMatch(strLine))
                                {
                                    if (strLine.Length < 20)//超过20个字的标题，可能是小说里面出现的“书中书、文中文”...
                                    {
                                    	t=strLine.Trim().Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
                                    	 
						                ToolStripItem fd = contentsToolStripMenuItem.DropDownItems.Add(t);
						
						                fd.Click += new System.EventHandler(ContentsToolStripMenuItemClick);
                                       // this.listBox1.Items.Add(strLine.Trim().Replace("\r\n", "").Replace("\r", "").Replace("\n", ""));//添加标题行
                                    }
                                    continue;
                                }                             
                            }
                            strLine = sr.ReadLine();
                            //Thread.Sleep(1);
                        }
                       
                }
            
            catch { }
        }
		void ContentsToolStripMenuItemClick(object sender, EventArgs e)
		{
			 String name = ((ToolStripMenuItem)sender).Text;
            FindTags(name);
		}
		//跳转书签，章节
		private void FindTags(string name)
        {
            try
            {
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrWhiteSpace(name))
                {
                    richTextBox1.Focus();
                    richTextBox1.Find(name);
                    richTextBox1.ScrollToCaret();
                }
            }
            catch { }
        }
		public string BaseDirectory = System.AppDomain.CurrentDomain.BaseDirectory + "ini/";//配置文件所在路径
        //加载书签
        private void LoadBookmark()
        {
            bMToolStripMenuItem.DropDownItems.Clear();

            string file = BaseDirectory + "bookmark.txt";
            if (File.Exists(file))
            {
            	string[] line =File.ReadAllLines(file);
            	for (int i = 0; i < line.Length; i++) {
            		string shu=line[i];
                        if (!string.IsNullOrEmpty(shu) && !string.IsNullOrWhiteSpace(shu))
                        {
                            ToolStripItem fd = bMToolStripMenuItem.DropDownItems.Add(shu);
                            fd.Click += new System.EventHandler(dsToolStripMenuItem_Click);
                        }
            	}
            }
        }
        //删除书签
        private void DeleteBookmark()
        {
            try
            {
                bMToolStripMenuItem.DropDownItems.Clear();

                string file = BaseDirectory + "bookmark.txt";
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
            }
            catch { }
        } 
		 //记录上一次打开txt文件的路径，这样在下一次运行时直接调用此路径，不用再次手动选择txt文件，除非txt文件位置或文件名发生改变
        private void RememberTxt(string txt)
        {
            try
            {
                if (!string.IsNullOrEmpty(txt) && !string.IsNullOrWhiteSpace(txt))
                {
                    FileStream fs = new FileStream(BaseDirectory + "my.txt", FileMode.Create);
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.WriteLine(txt);
                        sw.Close();
                        fs.Close();
                    }
                }
            }
            catch { }
        }
        //载入图书(自动)
        private void LoadRememberedTxt()
        {
            try
            {
                string file = BaseDirectory + "my.txt";
                if (File.Exists(file))
                {
                	string extension =  System.IO.Path.GetExtension(file).ToLower();
                	if (extension==".txt") {
                		FileStream fs = new FileStream(file, FileMode.Open);//打开保存记录的文件
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        String fileName = sr.ReadLine();//读取txt打开记录
                        if (!string.IsNullOrEmpty(fileName) && !string.IsNullOrWhiteSpace(fileName))//判断是否有记录
                        {
                            if (File.Exists(fileName))//判断是否有文件
                            {
                                this.Text = System.IO.Path.GetFileName(fileName);
                                this.richTextBox1.LoadFile(fileName, RichTextBoxStreamType.PlainText);//读取txt文件
                                LoadChapter(fileName);//读取章节
                            }
                        }
                        sr.Close();
                        fs.Close();
                    }
                    LoadBookmark();//加载书签
                	}
//                    else if (extension==".epub") {
//                		 
//                    	EpubBook book = EpubReader.Read(file);
//			
//					// Read metadata
//					string title = book.Title;
//					notifyIcon1.Text= title ;
//					 
//					 string text = book.ToPlainText();
//					 richTextBox1.Text=text;
//                    
//                    RememberTxt(file);//记录txt文件的路径
//                    LoadChapter2(text);//读取章节
//                  //  DeleteBookmark();//删除书签(防止打开B小说，却加载了A小说书签的bug)
//                    }
                }
            }
            catch { }
        }
		 //点击书签 定位到书签位置
        private void dsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String name = ((ToolStripMenuItem)sender).Text;
            FindTags(name);
        }
		void BookmarkToolStripMenuItemClick(object sender, EventArgs e)
		{
			if (richTextBox1.SelectedText != "")
            {
                string shu = StrTooLong(richTextBox1.SelectedText.Trim());

                if (!File.Exists(BaseDirectory + "bookmark.txt"))
            {
                FileStream fs = new FileStream(BaseDirectory + "bookmark.txt", FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(shu);
                //记得要关闭！不然里面没有字！
                sw.Close();
                fs.Close();
            }
            else
            {  
                StreamWriter sw = File.AppendText(BaseDirectory + "bookmark.txt");
                sw.WriteLine(shu);
                sw.Close();
                 
            }
                MessageBox.Show("书签已经存储！！");
               // bMToolStripMenuItem.DropDownItems.Clear();
                ToolStripItem fd = bMToolStripMenuItem.DropDownItems.Add(shu);

                fd.Click += new System.EventHandler(dsToolStripMenuItem_Click);
            }
		}
		//控制标签字符串长度为10个字
        private string StrTooLong(string str)
        {
            string temp = str.Replace(" ", "|").Replace("\r\n", "|").Replace("\r", "|").Replace("\n", "|");
            string[] arr = temp.Split('|');
            string shu = "";
            foreach (var item in arr)
            {
                if (!string.IsNullOrEmpty(item.Trim()))
                {
                    if (item.Length <= 10)
                    {
                        shu = item;
                    }
                    else
                    {
                        shu = item.Substring(0, 10);
                    }
                    break;
                }
            }
            return shu;
        }
		void HistoryToolStripMenuItemClick(object sender, EventArgs e)
		{
			string file = BaseDirectory + "History.txt";
                if (File.Exists(file))
                {
                	string[] txt=File.ReadAllLines(file);
                	//MessageBox.Show(txt);
                	FindTags(txt[0]);
                }
		}
		void ExitToolStripMenuItemClick(object sender, EventArgs e)
		{
			this.Close();
		}
		public void RememberHistory(){
			try
            {
				int start = richTextBox1.GetCharIndexFromPosition(new Point(0, 0));
				int end = richTextBox1.GetCharIndexFromPosition(new Point(richTextBox1.ClientSize.Width, richTextBox1.ClientSize.Height-1));
				var displayedText = richTextBox1.Text.Substring(start,end-start);
				string txt=StrTooLong(displayedText);
				
                if (!string.IsNullOrEmpty(txt) && !string.IsNullOrWhiteSpace(txt))
                {
                    FileStream fs = new FileStream(BaseDirectory + "History.txt", FileMode.Create);
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                    	
                        sw.WriteLine(txt);
                        sw.Close();
                        fs.Close();
                    }
                }
            }
            catch { }
		}
		void MainFormFormClosing(object sender, FormClosingEventArgs e)
		{
			RememberHistory();
		}
		int n=0;
		bool flag=false;
		void HideToolStripMenuItemClick(object sender, EventArgs e)
		{
			if (n%2==0) {
				hideToolStripMenuItem.Text="鼠标离开隐藏on";
				flag=true;
				
			}else{
				hideToolStripMenuItem.Text="鼠标离开隐藏off";
				flag=false;
			}
			n++;
		}
		 
		void Panel1MouseHover(object sender, EventArgs e)
		{
			if (flag) {
				this.Height=h;
			}
		}
		void Panel1MouseLeave(object sender, EventArgs e)
		{
			if (flag) {
				this.Height=splitContainer1.Panel1.Height;
			}
		}
		 
		 //执行热键
        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            //按快捷键 
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    switch (m.WParam.ToInt32())
                    {
                        case 100://按下的是Alt+1 
                            BossKey();//老板键
                            break;
                        case 200://按下的是Alt+1 
                            richTextBox1.Visible=true;
                            break; 
                        case 300://按下的是Alt+1 
                            this.Close();
                            break; 
                         case 400://按下的是Alt+1 
                           // SendKeys.Send("{PGDN}");
                           this.FindUp(richTextBox1, Clipboard.GetText());
                            break; 
                          case 500://按下的是Alt+1 
                           
                           this.FindDown(richTextBox1, Clipboard.GetText());
                            break; 
                    }
                    break;
            }
            base.WndProc(ref m);
        }
        //老板键：显示|隐藏 窗体
        private void BossKey()
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Minimized;
                this.Hide();//隐藏窗体
                this.notifyIcon1.Visible = true; //使托盘图标可见
            }
            else
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.notifyIcon1.Visible = false;
            }
        }
		void HelpToolStripMenuItemClick(object sender, EventArgs e)
		{
			MessageBox.Show("Alt+Q退出程序\nAlt+W老板键\npagedown翻页");
		}
		void MainFormActivated(object sender, EventArgs e)
		{
			HotKey.RegisterHotKey(Handle, 100, HotKey.KeyModifiers.Alt, Keys.W);//注册热键 Alt+1 老板键 我用着顺手
			 HotKey.RegisterHotKey(Handle, 200, HotKey.KeyModifiers.Alt, Keys.E); //显示
			 HotKey.RegisterHotKey(Handle, 300, HotKey.KeyModifiers.Alt, Keys.Q); //退出
			 HotKey.RegisterHotKey(Handle, 400,HotKey.KeyModifiers.Alt, Keys.Up); //翻页
			 HotKey.RegisterHotKey(Handle, 500,HotKey.KeyModifiers.Alt, Keys.Down); //翻页
			  
		}
		void MainFormLeave(object sender, EventArgs e)
		{
			HotKey.UnregisterHotKey(Handle, 100);//注销Id号为100的热键设定
		}
		void FontToolStripMenuItemClick(object sender, EventArgs e)
		{
			fontDialog1.ShowDialog();
            richTextBox1.Font = fontDialog1.Font;
		}
        //**********************
        int start = 0; int sun = 0; int count = 0;
        private void FindDown(RichTextBox rbox, string str)
        {
            int rbox1 = rbox.Text.Length;
            if (start < rbox1)
            {
                start = rbox.Find(str, start, RichTextBoxFinds.None);
                int los = rbox.SelectionStart + str.Length;
                if ((start < 0) || (start > rbox1))
                {
                    if (count == 0)
                    {
                       // this.seeks(str);
                        start = los;
                        sun = 0;
                    }
                    else
                    {
                      //  this.seeks(str);
                        start = los;
                        sun = 0;
                    }
                }
                else if (start == rbox1 || start < 0)
                {
                   // this.seeks(str);
                    start = los;
                    sun = 0;
                }
                else
                {
                    sun++;
                    start = los;
                    rbox.Focus();
                }
            }
            else if (start == rbox1 || start < 0)
            {
                int los = rbox.SelectionStart + str.Length;
              //  this.seeks(str);
                start = los;
                sun = 0;
            }
            else
            {
                int los = rbox.SelectionStart + str.Length;
              //  this.seeks(str);
                start = los;
                sun = 0;
            }
        }
        //向上查找函数
        private void FindUp(RichTextBox rbox, string str)
        {
            int rbox1 = rbox.SelectionStart;
            int index = rbox.Find(str, 0, rbox1, RichTextBoxFinds.Reverse);
            if (index > -1)
            {
                rbox.SelectionStart = index;
                rbox.SelectionLength = str.Length;
                sun++;
                rbox.Focus();
            }
            else if (index < 0)
            {
               // seeks(str);
                sun = 0;
               // rbox.SelectionStart = rbox.Text.Length;
            }
        } 
		void FinddownToolStripMenuItemClick(object sender, EventArgs e)
		{
			this.FindDown(richTextBox1, Clipboard.GetText());
		}
		void FindupToolStripMenuItemClick(object sender, EventArgs e)
		{
			this.FindUp(richTextBox1, Clipboard.GetText());
		}
		void RichTextBox1DoubleClick(object sender, EventArgs e)
		{
			HideCaret(richTextBox1.Handle);
			
			MouseEventArgs Mouse_e = (MouseEventArgs)e;  
			if(Mouse_e.Button == MouseButtons.Left){
					SendKeys.Send("{PGDN}");
					
			}
		}
		void RichTextBox1MouseDown(object sender, MouseEventArgs e)
		{
			HideCaret(richTextBox1.Handle);
		}
		void RichTextBox1MouseMove(object sender, MouseEventArgs e)
		{
			HideCaret(richTextBox1.Handle);
		}
		void RichTextBox1KeyUp(object sender, KeyEventArgs e)
		{
			HideCaret(richTextBox1.Handle);
		}
        //***************************
	}
}
